﻿using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler.Conditional
{
	/// <summary>
	/// 判断多个属性和值是否相等的Handler
	/// </summary>
	public class IsEqualsHandler : IsEqualHandler
	{
		public override bool IsCondition ( object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var propertyList = this.Property;
			if ( propertyList.IsNullOrEmpty ( ) )
			{
				return false;
			}
			var compareValues = this.GetCompareValues ( rootParamObject, parentParamObject, context );
			if ( compareValues.IsNullOrEmpty ( ) )
			{
				return false;
			}
			if ( propertyList.Length != compareValues.Count )
			{
				return false;
			}
			var compareValueEnumerator = compareValues.GetEnumerator ( );
			compareValueEnumerator.MoveNext ( );
			var joinType = this.Element.JoinType;
			foreach ( var property in propertyList )
			{
				var propertyValue = this.GetExpressionValue
				(
					this.GetPropertyName ( property, rootParamObject, parentParamObject, context )
					, rootParamObject
					, parentParamObject
					, context
				);
				propertyValue = this.GetConvertedValue ( propertyValue );
				var compareValue = this.GetConvertedValue ( compareValueEnumerator.Current );
				var compareResult = _compareFunction ( propertyValue, compareValue );
				switch ( joinType )
				{
					case ConditionJoinTypes.Or:
						if ( compareResult )
						{
							return true;
						}
						break;

					case ConditionJoinTypes.And:
						if ( !compareResult )
						{
							return false;
						}
						break;
				}
				compareValueEnumerator.MoveNext ( );
			}
			return joinType == ConditionJoinTypes.And;
		}
	}
}
